<template>
  <div>
    <el-table
      v-loading="listLoading"

      :data="listData"
      element-loading-text="加载中"
      border
      fit
      highlight-current-row
      stripe
      :span-method="objectSpanMethod"
      @sort-change="sortChanged"
      @row-click="rowClick"
    >
      <el-table-column
        v-for="(column,index) in columns"
        v-if="!column.hidden"
        :key="index"
        header-align="center"
        :prop="column.key"
        :label="column.label"
        :sortable="column.sortable"
        :align="column.align || 'center'"
        :width="column.width"
        :min-width="column.minWidth"
        :max-width="column.maxWidth"
        :show-overflow-tooltip="!column.type"
        :fixed="$store.state.app.device !== 'mobile' ? column.fixed : undefined"
      >
        <template slot-scope="scope" :class="column.type">
          <div v-if="column.type == 'sort'">
            <el-button  class="el-icon-top" @click="changeDataSort(scope.$index,-1)" />
            <el-button  class="el-icon-bottom" @click="changeDataSort(scope.$index,1)" />
          </div>
          <slot v-else-if="column.type == 'image' && !scope.row[column.key]">暂无图片</slot>
          <img
            v-else-if="column.type == 'image'"
            style="max-height: 30px;"
            :src="(scope.row[column.key].indexOf('//')< 0 ? $media: '') + scope.row[column.key] +'?x-oss-process=image/resize,h_30'"
            @click="selectImg(scope.row[column.key],column.type)"
          >
          <slot v-else-if="column.type == 'video' && !scope.row[column.key]">暂无视频</slot>
          <img
            v-else-if="column.type == 'video'"
            style="max-height: 30px;"
            :src="(scope.row[column.key].indexOf('//')< 0 ? $media: '') + scope.row[column.key] + '?x-oss-process=video/snapshot,t_1000,h_30,m_fast,f_jpg'"
            @click="selectImg(scope.row[column.key],column.type)"
          >
          <el-switch
            v-else-if="column.type == 'switch'"
            v-model="scope.row[column.key]"
            active-color="#13ce66"
            :active-value="switchData.yes"
            :inactive-value="switchData.no"
            inactive-color="#ff4949"
          />
          <slot v-else :name="column.key" :index="scope.$index" :row="scope.row" :column="column">
            <i
              v-if="(column.key.indexOf('Time') >= 0 || column.key.indexOf('Date') >= 0) && scope.row[column.key]"
              class="el-icon-time"
            />
            {{ format != null && typeof (format[column.key]) != 'undefined' ? format[column.key](scope.row, scope.$index) : scope.row[column.key] }}
          </slot>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisibleImg" destroy-on-close>
      <img :src="(fileUrl.indexOf('//')<0 ? $media : '') + fileUrl" width="100%">
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleVideo" destroy-on-close>
      <video
        preload="auto"
        :src="(fileUrl.indexOf('//')<0 ? $media : '') + fileUrl"
        width="100%"
        controls="controls"
      />
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="limitQuery.current"
      :limit.sync="limitQuery.size"
      @pagination="fetchData"
    />
  </div>
</template>

<script>

import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getBaseList } from '@/api/common'
import qs from 'qs'

export default {
  name: 'BaseList',
  components: { Pagination },
  props: {
    url: { type: String, default: '' },
    query: { type: Array, default: () => [] },
    columns: { type: Array, default: () => [] },
    format: {
      type: Object, default: () => {
      }
    },
    sortChange: {
      type: Function, default: () => {
      }
    },
    rowClick: {
      type: Function, default: () => {
      }
    },
    append: {
      type: Object, default: () => {
      }
    },
    spanColumn: { type: String },
    entity: {
      type: Object, default: () => {
        return { id: undefined }
      }
    }
  },
  data: () => {
    return {
      limitQuery: {
        current: 1,
        size: 20,
        ascs: [],
        descs: []
      },
      total: 0,
      listData: [],
      listLoading: false,
      dialogVisibleImg: false,
      dialogVisibleVideo: false,
      spanArr: [],
      spanColumns: [],
      switchData: { yes: 1, no: 2 },
      fileUrl: ''
    }
  },
  watch: {
    columns: {
      immediate: true,
      handler(newVal, oldVal) {
        newVal.forEach(e => {
          this.spanColumns.push(e.spanFlag)
        })
      }
    }
  },
  methods: {
    changeDataSort(rowIndex, next) {
      const nextIndex = rowIndex + next
      if (nextIndex > -1 && nextIndex < this.dataList.length) {
        this.sortChange(
          this.dataList[rowIndex].id, this.dataList[rowIndex].sortBy,
          this.dataList[nextIndex].id, this.dataList[nextIndex].sortBy
        )
      }
    },
    fetchData(page) {
      this.listLoading = true
      page && typeof (page) === 'number' && (this.limitQuery.page = page)
      const conditions = this.query.filter(e => e.value)
      const request = Object.assign({}, { conditions: conditions }, { page: this.limitQuery })

      getBaseList(this.url, {request: encodeURI(JSON.stringify(request))}).then(response => {
        this.listData = response.data.records
        if (this.spanColumn) {
          const spanArr = []
          let sid = -1
          this.listData.forEach(e => {
            if (e[this.spanColumn] !== sid) {
              spanArr.push(e.row)
              sid = e[this.spanColumn]
            } else {
              spanArr.push(0)
            }
          })
          this.spanArr = spanArr
        }
        this.total = response.data.total
        this.listLoading = false
      }).catch(err => {
        console.error(err)
        this.listLoading = false
      })
    },
    sortChanged(val) {
      const prop = val.prop
      if (val.order === 'ascending') {
        this.limitQuery.ascs = [prop]
        this.limitQuery.descs = []
      } else {
        this.limitQuery.ascs = []
        this.limitQuery.descs = [prop]
      }
      this.fetchData()
    },
    selectImg(val, type) {
      if (!val) {
        return
      }
      if (type === 'image') {
        this.dialogVisibleImg = true
      }
      if (type === 'video') {
        this.dialogVisibleVideo = true
      }
      this.fileUrl = val
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (this.spanColumn && this.spanColumns[columnIndex]) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0

        return {
          rowspan: _row,
          colspan: _col
        }
      }
    }
  }
}
</script>

